

package View;


import Controller.ControllerAssist;
import Controller.ControllerList;
import Model.Mysql;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetMetaData;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class NewClient extends javax.swing.JFrame {

   private Mysql mysql;
   private int code;
   private boolean pass = true;
   private boolean change;
   private int codeToChange = -1;


    public NewClient(Mysql mysql) {
    initComponents();
    buttonTrash.setVisible(false);
    this.mysql = mysql;
    code = -1;
    
    dateDay.setDate(Calendar.getInstance().getTime());
    change = false;

    }
    
    
    public NewClient(Mysql mysql, int codeSelected){
        initComponents();
        titleLabel.setText(""+"Modificar Empleado");
        this.mysql = mysql;
        change = true;
        this.codeToChange = codeSelected;
        
        
         // extrae la informacion de la base de datos 
         
     try {

                // coneccion a la base de datos
      

                mysql.resultSet = mysql.st.executeQuery( "SELECT name, last, restaurant, departamento, date_beginning, barCode FROM employee where code="+codeSelected);
                mysql.metaData = (ResultSetMetaData) mysql.resultSet.getMetaData();
                int numerodecolumnas = mysql.metaData.getColumnCount();

            while (mysql.resultSet.next()){

                for(int i=1;i<=numerodecolumnas;i++){
                    switch(i){
                        // creo este switch par delimitar el nombre de los label ya establecidos :D
                        case 1:
                            fieldName.setText(""+mysql.resultSet.getObject(i));
                        break;
                        case 2:
                            fieldLast.setText(""+mysql.resultSet.getObject(i));
                        break;
                        case 3:
                            fieldRestaurant.setText(""+mysql.resultSet.getObject(i));
                        break;
                        case 4:
                            fieldDepartment.setText(""+mysql.resultSet.getObject(i));
                        break;
                        case 5:
                            dateDay.setDate(mysql.resultSet.getDate(i));
                        break;
                        case 6:
                            fieldCode.setText(""+mysql.resultSet.getObject(i));
                        default:
                            ;
                        break;

                    }

                } // fin del for
            } // fin del while

                } catch (SQLException ex) {
                    Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);

                }

            }

    private NewClient() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

  
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fieldName = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        fieldCode = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        titleLabel = new javax.swing.JLabel();
        fieldLast = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        fieldRestaurant = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        fieldDepartment = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        dateDay = new com.toedter.calendar.JDateChooser();
        jLabel7 = new javax.swing.JLabel();
        buttonTrash = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        fieldName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldNameActionPerformed(evt);
            }
        });
        fieldName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldNameKeyTyped(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/aceptar.png"))); // NOI18N
        jButton1.setText("Ingresar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Nombre");

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancelar.png"))); // NOI18N
        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel6.setText("Codigo_Barra");

        fieldCode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldCodeActionPerformed(evt);
            }
        });
        fieldCode.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldCodeKeyTyped(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 102, 0));

        titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        titleLabel.setForeground(new java.awt.Color(255, 255, 255));
        titleLabel.setText("Nuevo Empleado ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        fieldLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldLastActionPerformed(evt);
            }
        });
        fieldLast.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldLastKeyTyped(evt);
            }
        });

        jLabel3.setText("Apellido");

        fieldRestaurant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldRestaurantActionPerformed(evt);
            }
        });
        fieldRestaurant.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldRestaurantKeyTyped(evt);
            }
        });

        jLabel4.setText("Restaurante");

        fieldDepartment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldDepartmentActionPerformed(evt);
            }
        });
        fieldDepartment.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldDepartmentKeyTyped(evt);
            }
        });

        jLabel5.setText("Departamento");

        jLabel7.setText("Fecha de Inicio");

        buttonTrash.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/trash.png"))); // NOI18N
        buttonTrash.setText("Eliminar");
        buttonTrash.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonTrashActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(buttonTrash)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 81, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel6))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(fieldCode))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(19, 19, 19)
                                .addComponent(dateDay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5))
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fieldLast, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(fieldDepartment)
                            .addComponent(fieldRestaurant)
                            .addComponent(fieldName))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(fieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(fieldLast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(fieldRestaurant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(fieldDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateDay, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel7)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(fieldCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonTrash, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton3});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {dateDay, fieldCode, fieldDepartment, fieldLast, fieldName, fieldRestaurant});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void fieldNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldNameActionPerformed
       
}//GEN-LAST:event_fieldNameActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    if (!change)   {  
        try {
            Insertar();
            ControllerList.updateData();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);
        }
      
    }
    
    else {
        
        
         try {
            update();
            ControllerList.updateData();
            ControllerAssist.updateData();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        
       
    }
       

}//GEN-LAST:event_jButton1ActionPerformed

public void inDate(int cod){
       //Fecha
              Date date=(Date) dateDay.getDate(); 
              SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
              String fecha = format.format(date);
              mysql.Query("Update employee set Date_Beginning =\""+ fecha +"\" where code="+cod);
  }   


public void Insertar() throws FileNotFoundException{
    pass = true;
     try {
         
            int resultado = 0 ;
          
            
            PreparedStatement ps = null;
            ps = (PreparedStatement) mysql.connection.prepareStatement("insert into employee (name, last, restaurant, departamento, barcode) values (?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);

         
            ps.setString(1,fieldName.getText()); // con el ps genero lo qee voy a ingresar 
            //lo genero en orden el 1 va a ser el dato uno en este caso seria nombre 
            // y como nombre es varchar tonces sera string 
            
            ps.setString(2,fieldLast.getText()); // con el ps genero lo qee voy a ingresar 
            //lo genero en orden el 1 va a ser el dato uno en este caso seria nombre 
            // y como nombre es varchar tonces sera string 
            
            ps.setString(3,fieldRestaurant.getText()); 
            
            ps.setString(4,fieldDepartment.getText()); 
            
            try{
                int bCode = 0;
                
                bCode = Integer.parseInt(fieldCode.getText());
                
                ps.setInt(5,bCode); // si me da error 
                
            }catch(Exception e){
                
                pass = false;
                
            }
            
           

    
                  
      if (pass) {
            resultado = ps.executeUpdate();
            
            mysql.resultSet = ps.getGeneratedKeys();
                 while (mysql.resultSet.next()) {
                        code = mysql.resultSet.getInt(1); // obtengo el codigo. 
                
            }

                inDate(code);  // Ingreso la fecha 
                JOptionPane.showMessageDialog(rootPane, "Dato ingresado exitosamente ");
                dispose();   
                ps.close();
               
      }
      else {
          JOptionPane.showMessageDialog(rootPane, "Existe algun dato no coherente, rebise, porfavor. ");
      }
      
      
             }catch(SQLException e){
                 
                 JOptionPane.showMessageDialog(rootPane, "Error en la Base de Datos "+e.toString());
                  
       
           } // fin del catch
} // fin insertar 


public void update() throws FileNotFoundException{
    pass = true;
     try {
         
            int resultado = 0 ;
          
            
            PreparedStatement ps = null;
            ps = (PreparedStatement) mysql.connection.prepareStatement("UPDATE  employee SET name = ?, last =? , restaurant = ?, departamento = ?, barcode = ? WHERE code = "+codeToChange);

         
            ps.setString(1,fieldName.getText()); // con el ps genero lo qee voy a ingresar 
            //lo genero en orden el 1 va a ser el dato uno en este caso seria nombre 
            // y como nombre es varchar tonces sera string 
            
            ps.setString(2,fieldLast.getText()); // con el ps genero lo qee voy a ingresar 
            //lo genero en orden el 1 va a ser el dato uno en este caso seria nombre 
            // y como nombre es varchar tonces sera string 
            
            ps.setString(3,fieldRestaurant.getText()); 
            
            ps.setString(4,fieldDepartment.getText()); 
            
            try{
                int bCode = 0;
                
                bCode = Integer.parseInt(fieldCode.getText());
                
                ps.setInt(5,bCode); // si me da error 
                
            }catch(Exception e){
                
                pass = false;
                
            }
            
           

    
                  
      if (pass) {
            resultado = ps.executeUpdate();
            
            

                inDate(codeToChange);  // Ingreso la fecha 
                
                 JOptionPane.showMessageDialog(rootPane, "Listo, se han modificado los datos. ");
                 dispose();
               
                 ps.close();
               
      }
      else {
          JOptionPane.showMessageDialog(rootPane, "Existe algun dato no coherente, rebise, porfavor. ");
      }
      
      
             }catch(SQLException e){
                 
                 JOptionPane.showMessageDialog(rootPane, "Error en la Base de Datos "+e.toString());
                  
       
           } // fin del catch
} // fin insertar 
 
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        dispose();
      
       
    }//GEN-LAST:event_jButton3ActionPerformed

    private void fieldCodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldCodeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldCodeActionPerformed

    private void fieldNameKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldNameKeyTyped
    
    }//GEN-LAST:event_fieldNameKeyTyped

    private void fieldCodeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldCodeKeyTyped
       char c = evt.getKeyChar();
       if(!(Character.isDigit(c))|| c== evt.VK_BACK_SPACE || c==evt.VK_DELETE){
           getToolkit().beep();
           evt.consume();
       }
    }//GEN-LAST:event_fieldCodeKeyTyped

    private void fieldLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldLastActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldLastActionPerformed

    private void fieldLastKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldLastKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldLastKeyTyped

    private void fieldRestaurantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldRestaurantActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldRestaurantActionPerformed

    private void fieldRestaurantKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldRestaurantKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldRestaurantKeyTyped

    private void fieldDepartmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldDepartmentActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldDepartmentActionPerformed

    private void fieldDepartmentKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldDepartmentKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldDepartmentKeyTyped

    private void buttonTrashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTrashActionPerformed
        
        
        
        // Message
        
        
        //Custom button text
        Object[] options = {"Continuar",
                            "Cancelar",
                           };
        int opt = JOptionPane.showOptionDialog(rootPane,
            "¿Desea realmente borrar a "+fieldName.getText()+" "+fieldLast.getText()+"?", 
            "Confirmación de Borrar ",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[1]);
        
        

       

        if(opt == 0){
           mysql.Query("DELETE FROM employee WHERE code = "+codeToChange);
           JOptionPane.showMessageDialog(rootPane, "Listo, se ha eliminado este dato. ");
           ControllerList.updateData();
           dispose();
        }
        else if(opt == 1){

            }
        
       
    }//GEN-LAST:event_buttonTrashActionPerformed



    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonTrash;
    private com.toedter.calendar.JDateChooser dateDay;
    private javax.swing.JTextField fieldCode;
    private javax.swing.JTextField fieldDepartment;
    private javax.swing.JTextField fieldLast;
    private javax.swing.JTextField fieldName;
    private javax.swing.JTextField fieldRestaurant;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration//GEN-END:variables

}
